<template>
    <el-dialog :append-to-body="true" v-model="visible" width="822" :before-close="handleClose"
        class="recharge-center-dialog" center>

        <div class="content">
            <div class="left">
                <h3>充值中心<span>适用场景：云电脑、云游戏</span></h3>

                <el-row :gutter="20">
                    <el-col :span="8" v-for="(item, index) in rechargeOptions" :key="index">
                        <div class="grid-content" :class="{ active: selectedOption === index }"
                            @click="selectOption(item, index)">
                            <div class="bean-count">
                                <img src="@/assets/images/header/dou.png" width="16" alt="" />
                                {{ item.coin }}
                                云豆
                            </div>
                            <div class="bean-price"><span>¥</span>{{ item.price * 0.01 }}</div>
                            <div class="new-user-tag" v-if="item.tip">{{ item.tip }}</div>
                        </div>
                    </el-col>
                </el-row>

                <!-- 游戏推广横幅（轮播图） -->
                <el-carousel height="168px" indicator-position="none" arrow="always" :autoplay="true" :interval="4000"
                    v-if="bannerList.length" style="width: 100%;">
                    <el-carousel-item v-for="(banner, idx) in bannerList" :key="idx" style="width: 100%;">
                        <!-- <div class="banner-content">
                            <div class="banner-title">{{ banner.title || '云游戏 焕新升级！' }}</div>
                            <div class="banner-desc">{{ banner.desc || '新增多款游戏无需账号直接玩' }}</div>
                            <el-button class="play-now-btn" type="primary" @click="handleBannerClick(banner)">
                                <img src="@/assets/svgs/thunder.svg" alt="秒玩图标" />
                                秒玩
                            </el-button>
                        </div> -->
                        <img v-if="banner.imageUrl" :src="banner.imageUrl" alt="banner"
                            style="width: 100%;border-radius: 8px;" />
                    </el-carousel-item>
                </el-carousel>
            </div>
            <div class="right">
                <div class="payment-section">
                    <div class="payment-title">实付金额</div>
                    <div class="payment-amount"><span>¥</span>{{ selectedAmount }}</div>

                    <!-- 二维码支付区域 -->
                    <div class="qrcode-section">
                        <div class="qrcode-img" v-loading="qrLoading" style="position:relative;min-height:180px;">
                            <div class="qrcode-placeholder">
                                <QrcodeVue v-if="qrCodeImg" :value="qrCodeImg" :size="160" class="qr-code-img"
                                    style="overflow: hidden;" />
                            </div>
                        </div>
                        <div>同时支持支付宝、微信扫码支付</div>
                        <div class="payment-methods">
                            <img src="@/assets/images/alipay.png" alt="支付宝" class="payment-icon">
                            <img src="@/assets/images/wechat.png" alt="微信" class="payment-icon">
                        </div>
                    </div>

                    <!-- 订单号 -->
                    <div class="order-number">
                        <div class="order-label">订单号:</div>
                        <div class="order-value">{{ orderInfo?.orderNo }}</div>
                    </div>

                    <!-- 支付协议 -->
                    <div class="agreement-section" @click="handleAgreementClick">
                        购买即同意<a style="color:#4CE0EB ;">《雷电云电脑服务协议》</a>
                    </div>
                </div>
            </div>
        </div>

    </el-dialog>
</template>

<script setup>
import axios from "axios";
import md5 from 'js-md5';
import QrcodeVue from 'qrcode.vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

import { ref, onMounted, computed, watch } from 'vue'
import { getCoinPlanList, getBannerList, generateCoinOrder, queryOrderDetail, createPaymentOrder, generatePaymentQRCode } from '@/api/user';

const userStore = useUserStore()

// 充值选项数据
const rechargeOptions = ref([])

// 选中的选项
const selectedOption = ref(0)

// 游戏推广横幅数据
const bannerList = ref([])

// 是否同意协议
const agreed = ref(true)

// 订单号（模拟数据）
const orderInfo = ref({})

//增加定时器变量
let orderStatusTimer = null;

// 支付二维码图片URL
const qrLoading = ref(false)
const qrCodeImg = ref('');

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    }
})

// Emits
const emit = defineEmits(['update:modelValue', 'close'])

const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

// 监听弹窗显示，显示时初始化
watch(visible, (val) => {
    if (val) {
        GetCoinPlanList();
        GetBannerList();
    }
});;

// 获取充值选项列表
const GetCoinPlanList = async () => {
    getCoinPlanList().then((response) => {
        rechargeOptions.value = response.coinPlans || [];
        selectOption(rechargeOptions.value[0], 0)
    }).catch((error) => {
        console.error('获取充值选项失败:', error);
    });
}

// 获取游戏推广横幅列表
const GetBannerList = async () => {
    let panamr = {
        "location": "recharge"
    };
    getBannerList(panamr).then((response) => {
        bannerList.value = response.banners || [];
        // 这里可以处理横幅数据，比如显示在页面上
    }).catch((error) => {
        console.error('获取充值横幅失败:', error);
    });
}
// 轮播图点击事件（可根据实际需求跳转或埋点）
const handleBannerClick = (banner) => {
    if (banner && banner.link) {
        window.open(banner.link, '_blank');
    }
}


// 选中的金额
const selectedAmount = computed(() => {
    const item = rechargeOptions.value[selectedOption.value];
    return item ? (item.price * 0.01).toFixed(2) : '0.00';
})

// 选择充值选项
const selectOption = (item, index) => {
    selectedOption.value = index;
    let params = {
        "planId": item.id
    };
    generateCoinOrder(params).then((response) => {
        orderInfo.value = response.orderInfo || '生成订单失败';
        setQRCode();
        setqueryOrderDetail()
    }).catch((error) => {
        console.error('生成订单或二维码失败:', error);
    });
}

//查询订单详情
const setqueryOrderDetail = async () => {
    const { orderNo } = orderInfo.value;
    if (!orderNo) return;

    // 清除旧定时器，防止重复
    if (orderStatusTimer) {
        clearTimeout(orderStatusTimer);
        orderStatusTimer = null;
    }

    let params = { "orderNo": orderNo };
    try {
        const response = await queryOrderDetail(params);
        console.log('查询订单详情:', response);
        const status = response?.order?.status;
        console.log(status);
        // 你可以根据实际接口结构调整
        if (status == 'paid') {
            //提示支付成功
            ElMessage({
                type: 'success',
                customClass: 'custom-success-message-icon',
                dangerouslyUseHTMLString: true,
                message: `支付成功`,
                offset: 65
            })
            // 已支付，关闭弹窗
            emit('close');
            // 获取用户信息
            userStore.setCoin()
        } else {
            // 继续轮询
            orderStatusTimer = setTimeout(setqueryOrderDetail, 2000); // 2秒轮询一次
        }
    } catch (error) {
        // 失败也继续轮询
        orderStatusTimer = setTimeout(setqueryOrderDetail, 2000);
        console.error('查询订单详情失败:', error);
    }
};

//生成支付二维码
const setQRCode = async () => {
    qrLoading.value = true;
    const { orderNo, orderName, amount } = orderInfo.value;
    console.log(orderInfo.value);
    console.log(orderNo, orderName, amount);
    if (!orderNo) {
        return;
    }

    // 固定参数
    const platform = "20800_20801";
    const gameName = "2406";
    const ver = "1";
    const gameKey = "8001669788f14426b1594c8bc2e79645";

    // Base64 编码
    function base64Encode(str) {
        return btoa(unescape(encodeURIComponent(str)));
    }

    console.log(userStore.uid);

    // 业务参数
    const userId = userStore.uid; // 可根据实际情况动态获取
    const userName = "null";
    const productName = encodeURIComponent(orderName);
    const serverID = "23";
    const roleID = "-1";
    const gameOrderId = orderNo; // 用订单号

    // 构建 auth 字符串
    const authStr = `userid=${userId}&userName=${userName}&productName=${productName}&amount=${amount || 1}&serverID=${serverID}&roleID=${roleID}&game_order_id=${gameOrderId}`;
    console.log(authStr);
    const authBase64 = base64Encode(authStr);

    // 使用
    const time = getNowTimeStr(); // 结果如 20250909182933
    const verifyStr = authBase64 + time + gameKey;
    const verify = md5(verifyStr); // 直接用 js-md5
    console.log(time);

    const headers = {
        "X-Channel": "20800",
        "X-SubChannel": "20801",
    };

    try {
        const response = await axios.post("https://test-ldcloud.changzhi.top/unifiedorder", null, {
            params: {
                platform,
                gameName,
                ver,
                time,
                auth: authBase64,
                verify,
            },
            headers,
        });
        // 处理二维码URL
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(response.data, "text/xml");
        const billnoNode = xmlDoc.getElementsByTagName('billno')[0];
        const billno = billnoNode ? billnoNode.textContent : '';

        console.log('billno:', billno);
        setgeneratePaymentQRCode(billno);

        console.log("Response:", response.data);
    } catch (error) {
        qrLoading.value = false;
        qrCodeImg.value = '';
        console.error("请求失败", error);
    }
}
//生成支付二维码
const setgeneratePaymentQRCode = async (orderId) => {
    if (!orderId) return;
    try {
        const res = await axios.post('https://test-ldcloud.changzhi.top/qr/generate', { orderId });
        if (res.data && res.data.code === 200 && res.data.data && res.data.data.qrCodeUrl) {
            qrCodeImg.value = res.data.data.qrCodeUrl;
            qrLoading.value = false;
            console.log('二维码生成成功:', qrCodeImg.value);
        } else {
            qrCodeImg.value = '';
            qrLoading.value = false;
            console.error('二维码生成失败', res.data.message);
        }
    } catch (e) {
        qrLoading.value = false;
        qrCodeImg.value = '';
        console.error('二维码生成异常', e);
    }
}


// 方法
const handleClose = () => {
    if (orderStatusTimer) {
        clearTimeout(orderStatusTimer);
        orderStatusTimer = null;
    }
    emit('close')
}

// 生成时间字符串
const getNowTimeStr = () => {
    const now = new Date();
    const pad = (n) => n.toString().padStart(2, '0');
    return (
        now.getFullYear().toString() +
        pad(now.getMonth() + 1) +
        pad(now.getDate()) +
        pad(now.getHours()) +
        pad(now.getMinutes()) +
        pad(now.getSeconds())
    );
}

// 协议点击事件
const handleAgreementClick = () => {
    var url = 'https://www.ldyuncs.com/ldy/pcpolicy/purchase_policy.html';
    // 发送消息给C#后端
    window.chrome.webview.postMessage({
        action: 'openExternalBrowser',
        url: url
    });
}

</script>


<style lang="scss">
.recharge-center-dialog {
    background: #141414 url('@/assets/images/rechange_right_bg.png') no-repeat !important;
    background-position: top right !important;
    border-radius: 4px;

    .el-dialog__header {
        padding: 20px !important;
        border-bottom: none;

        .el-dialog__title {
            color: #fff;
            font-size: 18px;
        }

        .el-dialog__headerbtn .el-dialog__close {
            color: #fff;
        }
    }

    .el-dialog__body {
        color: #fff;

        .content {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;

            .left {
                flex: 1;
                padding: 0 40px 38px;

                h3 {
                    font-size: 20px;
                    font-weight: bold;
                    color: #fff;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 30px;

                    span {
                        font-size: 12px;
                        color: #888;
                        font-weight: normal;
                    }
                }

                .el-row {
                    margin-bottom: 20px;
                }

                .grid-content {
                    height: 104px;
                    background: #2a2a26 url('@/assets/images/Union.png') no-repeat;
                    // background: linear-gradient(90deg, #2a2a26 0%, #2a2a26 50%);
                    background-position: top right !important;

                    border-radius: 4px;
                    padding: 20px;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    position: relative;
                    text-align: center;
                    border: 2px solid transparent;
                    margin: 10px 0;
                    box-sizing: border-box;

                    &.active {
                        border-color: #ffe500;
                        background: rgba(255, 229, 0, 0.1);
                    }

                    .bean-count {
                        font-size: 16px;
                        font-weight: bold;
                        color: #fff;
                        margin-bottom: 4px;
                    }

                    .bean-price {
                        font-size: 24px;
                        color: #fff;
                        font-weight: bold;

                        span {
                            font-size: 13px;
                        }
                    }

                    .new-user-tag {
                        width: 92px;
                        height: 22px;
                        line-height: 22px;
                        position: absolute;
                        top: -11px;
                        left: 0;
                        background: linear-gradient(135deg, #fb4529 0%, #ff874e 100%);
                        color: #fff;
                        border-radius: 8px 8px 8px 0;
                        font-size: 12px;
                    }
                }

                // 游戏推广横幅
                .promotion-banner {
                    height: 158px;
                    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
                    border-radius: 12px;
                    padding: 20px;
                    margin-top: 30px;
                    position: relative;
                    overflow: hidden;
                    display: flex;
                    align-items: flex-end;
                    box-sizing: border-box;

                    &::before {
                        content: '';
                        position: absolute;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        // background: url('@/assets/images/game_icons.png') no-repeat;
                        background-size: contain;
                        opacity: 0.3;
                    }

                    .banner-content {
                        position: relative;
                        z-index: 1;
                        display: flex;
                        flex-direction: column;
                        align-items: flex-start;
                        gap: 8px;
                        flex: 1;

                        .banner-title {
                            font-size: 18px;
                            font-weight: bold;
                            color: #fff;
                            margin-bottom: 4px;
                        }

                        .banner-desc {
                            font-size: 14px;
                            color: rgba(255, 255, 255, 0.8);
                        }

                        .play-now-btn {
                            background: rgba(255, 255, 255, 0.2) !important;
                            border: 1px solid rgba(255, 255, 255, 0.3);
                            color: #fff;
                            font-weight: bold;
                            border-radius: 20px;
                            padding: 6px 20px;
                            font-size: 14px;

                            &:hover {
                                background: rgba(255, 255, 255, 0.3);
                            }
                        }
                    }
                }
            }

            .right {
                width: 245px;
                padding: 20px;

                .payment-section {
                    color: #888;

                    .payment-title {
                        font-size: 12px;
                        margin-bottom: 8px;
                        text-align: center;
                    }

                    .payment-amount {
                        font-size: 32px;
                        font-weight: bold;
                        color: #fff;
                        margin-bottom: 20px;
                        text-align: center;

                        span {
                            font-size: 12px;
                        }
                    }

                    .qrcode-section {
                        text-align: center;
                        margin-bottom: 20px;

                        .qrcode-img {
                            // background: #363025;
                            padding: 10px;
                            border-radius: 8px;
                            display: inline-block;
                            margin-bottom: 15px;
                            // border: 1px solid linear-gradient(90deg, #2a2a26 0%, #2a2a26 50%);

                            .qrcode-placeholder {
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                position: relative;
                                padding: 7px;
                                background: #f0f0f0;
                                border-radius: 4px;
                                box-sizing: border-box;

                                .qr-code-img {
                                    width: 160px;
                                    height: 160px;
                                    display: block;
                                }
                            }

                            .qrcode-placeholder::after {
                                content: '';
                                position: absolute;
                                width: 198px;
                                height: 198px;
                                border: 2px solid #333;
                                // border: 1px solid linear-gradient(90deg, #2a2a26 0%, #2a2a26 50%);
                                border-radius: 4px;
                                box-sizing: border-box;
                            }
                        }

                        .payment-methods {
                            display: flex;
                            justify-content: center;
                            gap: 15px;

                            .payment-icon {
                                width: 24px;
                                height: 24px;
                                border-radius: 4px;
                                display: inline-block;
                            }
                        }
                    }

                    .order-number {
                        height: 77px;
                        padding: 10px;
                        border-radius: 4px;
                        background: #232527;
                        margin-bottom: 20px;
                        box-sizing: border-box;

                        .order-label {
                            font-size: 12px;
                            margin-bottom: 4px;
                        }

                        .order-value {
                            font-size: 12px;
                            border-radius: 4px;
                            word-break: break-all;
                        }
                    }

                    .agreement-section {
                        text-align: center;
                        font-size: 12px;
                        // .el-checkbox__input.is-checked .el-checkbox__inner {
                        //     background-color: #ffe500;
                        //     border-color: #ffe500;
                        // }

                        // .el-checkbox__input.is-checked+.el-checkbox__label {
                        //     color: #fff;
                        // }

                        // .el-checkbox__label {
                        //     color: #888;
                        //     font-size: 12px;
                        // }

                        a {
                            color: #888;
                            text-decoration: none;
                        }
                    }
                }
            }
        }
    }

    .el-dialog__footer {
        padding-top: 0 !important;
        padding-bottom: 38px;
        border-top: none;

        .el-button {
            width: 135px;
            height: 50px;
            background: #232527;
            border: #232527;
            color: #e2e2e2;
            font-size: 14px;
            font-weight: bold;

            &.el-button--primary {
                background: #ffe500;
                border-color: #ffe500;
                color: #121212;
            }
        }
    }
}

/* 自定义遮罩层的颜色和透明度 
.qrcode-img .el-loading-mask {
    background-color: rgba(0, 0, 0, 0.5);
}
*/
/* 自定义加载文字样式 */
.qrcode-img .el-loading-text {
    font-size: 18px;
    color: #ff6600;
}
</style>
